package controllers

import (
	"blog-backend/internal/app/dtos"
	"blog-backend/internal/app/services"
	"blog-backend/internal/utils"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type CategoryController struct {
	categoryService *services.CategoryService
}

func NewCategoryController() *CategoryController {
	return &CategoryController{
		categoryService: services.NewCategoryService(),
	}
}

// GetCategories 获取所有分类
// @Summary 获取所有分类
// @Description 获取所有分类列表
// @Tags 分类
// @Produce json
// @Success 200 {object} dtos.SuccessResponse{data=dtos.CategoryListResponse} "获取成功"
// @Failure 500 {object} dtos.ErrorResponse "服务器内部错误"
// @Router /api/categories [get]
func (c *CategoryController) GetCategories(ctx *gin.Context) {
	categories, err := c.categoryService.GetCategories()
	if err != nil {
		utils.RespondError(ctx, http.StatusInternalServerError, err.Error())
		return
	}

	// 构建响应DTO
	var categoryInfos []dtos.CategoryInfo
	for _, category := range categories {
		categoryInfos = append(categoryInfos, dtos.CategoryInfo{
			ID:   category.ID,
			Name: category.Name,
			Slug: category.Slug,
		})
	}

	utils.RespondJSON(ctx, http.StatusOK, dtos.SuccessResponse{
		Success: true,
		Message: "获取分类列表成功",
		Data: dtos.CategoryListResponse{
			Categories: categoryInfos,
			Total:      len(categoryInfos),
		},
	})
}

func (c *CategoryController) GetPopularCategories(ctx *gin.Context) {
	limit := 10
	categories, err := c.categoryService.GetPopularCategories(limit)
	if err != nil {
		utils.RespondError(ctx, http.StatusInternalServerError, err.Error())
		return
	}

	// 构建响应DTO
	var categoryInfos []dtos.CategoryInfo
	for _, category := range categories {
		categoryInfos = append(categoryInfos, dtos.CategoryInfo{
			ID:    category.ID,
			Name:  category.Name,
			Slug:  category.Slug,
			Count: category.Count,
		})
	}

	utils.RespondJSON(ctx, http.StatusOK, dtos.SuccessResponse{
		Success: true,
		Message: "获取热门分类成功",
		Data: dtos.CategoryListResponse{
			Categories: categoryInfos,
			Total:      len(categoryInfos),
		},
	})
}

// CreateCategory 创建分类
// @Summary 创建分类
// @Description 创建新分类
// @Tags 分类
// @Accept json
// @Produce json
// @Security Bearer
// @Param category body dtos.CreateCategoryDto true "分类信息"
// @Success 201 {object} dtos.SuccessResponse{data=dtos.CategoryInfo} "创建成功"
// @Failure 400 {object} dtos.ErrorResponse "请求参数错误"
// @Failure 401 {object} dtos.ErrorResponse "未认证"
// @Failure 409 {object} dtos.ErrorResponse "分类名称已存在"
// @Failure 500 {object} dtos.ErrorResponse "服务器内部错误"
// @Router /api/categories [post]
func (c *CategoryController) CreateCategory(ctx *gin.Context) {
	var dto dtos.CreateCategoryDto
	if err := ctx.ShouldBindJSON(&dto); err != nil {
		utils.RespondError(ctx, http.StatusBadRequest, err.Error())
		return
	}

	category, err := c.categoryService.CreateCategory(dto.Name)
	if err != nil {
		utils.RespondError(ctx, http.StatusConflict, err.Error())
		return
	}

	utils.RespondJSON(ctx, http.StatusCreated, dtos.SuccessResponse{
		Success: true,
		Message: "创建分类成功",
		Data: dtos.CategoryInfo{
			ID:   category.ID,
			Name: category.Name,
			Slug: category.Slug,
		},
	})
}

// UpdateCategory 更新分类
// @Summary 更新分类
// @Description 更新现有分类
// @Tags 分类
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path int true "分类ID"
// @Param category body dtos.UpdateCategoryDto true "更新信息"
// @Success 200 {object} dtos.SuccessResponse{data=dtos.CategoryInfo} "更新成功"
// @Failure 400 {object} dtos.ErrorResponse "请求参数错误"
// @Failure 401 {object} dtos.ErrorResponse "未认证"
// @Failure 404 {object} dtos.ErrorResponse "分类不存在"
// @Failure 409 {object} dtos.ErrorResponse "分类名称已存在"
// @Failure 500 {object} dtos.ErrorResponse "服务器内部错误"
// @Router /api/categories/{id} [put]
func (c *CategoryController) UpdateCategory(ctx *gin.Context) {
	id := ctx.Param("id")
	categoryID, err := strconv.ParseUint(id, 10, 32)
	if err != nil {
		utils.RespondError(ctx, http.StatusBadRequest, "无效的分类ID")
		return
	}

	var dto dtos.UpdateCategoryDto
	if err := ctx.ShouldBindJSON(&dto); err != nil {
		utils.RespondError(ctx, http.StatusBadRequest, err.Error())
		return
	}

	category, err := c.categoryService.UpdateCategory(uint(categoryID), dto.Name)
	if err != nil {
		status := http.StatusInternalServerError
		if err.Error() == "分类名称已存在" {
			status = http.StatusConflict
		} else if err.Error() == "分类不存在" {
			status = http.StatusNotFound
		}
		utils.RespondError(ctx, status, err.Error())
		return
	}

	utils.RespondJSON(ctx, http.StatusOK, dtos.SuccessResponse{
		Success: true,
		Message: "更新分类成功",
		Data: dtos.CategoryInfo{
			ID:   category.ID,
			Name: category.Name,
			Slug: category.Slug,
		},
	})
}

// DeleteCategory 删除分类
// @Summary 删除分类
// @Description 删除现有分类
// @Tags 分类
// @Produce json
// @Security Bearer
// @Param id path int true "分类ID"
// @Success 200 {object} dtos.SuccessResponse "删除成功"
// @Failure 400 {object} dtos.ErrorResponse "无效的分类ID"
// @Failure 401 {object} dtos.ErrorResponse "未认证"
// @Failure 403 {object} dtos.ErrorResponse "分类下有文章，无法删除"
// @Failure 404 {object} dtos.ErrorResponse "分类不存在"
// @Failure 500 {object} dtos.ErrorResponse "服务器内部错误"
// @Router /api/categories/{id} [delete]
func (c *CategoryController) DeleteCategory(ctx *gin.Context) {
	id := ctx.Param("id")
	categoryID, err := strconv.ParseUint(id, 10, 32)
	if err != nil {
		utils.RespondError(ctx, http.StatusBadRequest, "无效的分类ID")
		return
	}

	if err := c.categoryService.DeleteCategory(uint(categoryID)); err != nil {
		status := http.StatusInternalServerError
		if err.Error() == "分类下有文章，无法删除" {
			status = http.StatusForbidden
		} else if err.Error() == "分类不存在" {
			status = http.StatusNotFound
		}
		utils.RespondError(ctx, status, err.Error())
		return
	}

	utils.RespondJSON(ctx, http.StatusOK, dtos.SuccessResponse{
		Success: true,
		Message: "删除分类成功",
	})
}
